#
# CVSDialogs.py
#
# Simple Dialogs used in the SNiFF+ 3.x CVS Adapter
#
# Author: Martin Oberhuber
# Copyright (c) 1998, 1999 TakeFive Software, Salzburg
#
# Revisions:
#

import os,time
import CVSPrefs
import CVSCore

# Modules required for the Dialogs
from etgui import *
from etguiimpl import PotGuiPopupButton
from PageLayout import *
import YesNoDialog
#import CmdNo
#import ListEditor

#----------Helper functions----------------------------------------------

def TranslateAt(theString):
	return string.replace(theString, '@', '(a)')

def GetRootValue(model, RWE):
	# BUGBUG also add new Roots to the Translations List?
	result = model.GetValue("Root")
	if result[:5]=="ERROR":
		return None
	else:
		return result

def MakeRootButton(model, RWE, defaultRoot=""):
	theRoots = CVSPrefs.GetRepositories(RWE)
	if not defaultRoot:
		if len(theRoots) > 0:
			defaultRoot = theRoots[0]
		else:
			# no RWE, no defaultRoot
			if os.environ.has_key("CVSROOT"):
				defaultRoot = os.environ["CVSROOT"]
			else:
				defaultRoot = "ERROR - no CVSROOT set"
	rootPopup=PotGuiPopupButton("Root")
	hadDefault=0
	for cvsroot in theRoots:
		if cvsroot == defaultRoot:
			hadDefault=1
		rootPopup.AddItem(TranslateAt(cvsroot), cvsroot)
	if not hadDefault:
		rootPopup.AddItem(TranslateAt(defaultRoot), defaultRoot)
	model.SetValue("Root", defaultRoot)
	return MakeFieldLayout(rootPopup)

#----------Dialogs----------------------------------------------------------

class YesNoCancelDialog(YesNoDialog.YesNoDialog):
	def MakeContent(self):
		return MakeDialogWithButtons(
			self.text,
			ActionButton(CmdNo.cIdOk, 'Yes', default=1),
			ActionButton(CmdNo.cIdNo, 'No'),
			ActionButton(CmdNo.cIdCancel, 'Cancel')
		)
	def Cancel(self):
		self.answer = -1
	def Control(self,id,part,val):
		if id==CmdNo.cIdOk:
			self.answer = 1
			return 0
		elif id==CmdNo.cIdCancel:
			self.answer = -1
			return 0
		elif id==CmdNo.cIdNo:
			self.answer = 0
		return 0

def AskYesNo(title, text):
	dlg = YesNoDialog.YesNoDialog(title, text)
	ShowDialog(dlg)
	return dlg.Answer()

def AskYesNoCancel(title, text):
	dlg = YesNoCancelDialog(title, text)
	ShowDialog(dlg)
	return dlg.Answer()

def GuessRepositoryDialog(RWE, localRelative, defaultRelative="", defaultRoot=""):
	"""Ask the user for correct Repository / Root combination to use"""
	from etgui import *
	from PageLayout import *
	if not defaultRelative: defaultRelative=localRelative
	if not defaultRoot: defaultRoot=CVSCore.GetLastValidRoot(RWE)
	if not CVSPrefs.AlwaysShowRepDialog:
		return (defaultRoot, defaultRelative)
	model = PotGuiModel()
	model.SetValue("Relative", defaultRelative)
	retval=ShowSubDialog("Please Enter CVS Repository for "+localRelative,
		model,
		MakeSectionLayout(
			Form(
				items=[
					"Local Path:", TextItem(localRelative),
					"CVSROOT:", MakeRootButton(model, RWE, defaultRoot),
					"Repository Path:", PotTextField("Relative")
				]
			)
		)
	)
	if CVSPrefs.TEST: print "(CVSCore)\tRepositoryDialog @BretValue: @b%d@x@B" % retval
	if retval:
		newRoot = model.GetValue("Root")
		newRelative = model.GetValue("Relative")
		return (newRoot, newRelative)
	else:
		return None

def GetRepositoryDialog(RWE, Heading):
	"""Dialog to choose the CVSROOT; returns the Root or None"""
	model = PotGuiModel()
	retval=ShowSubDialog(Heading,
		model,
		MakeSectionLayout(
			Form(
				items=[
					"CVSROOT:", MakeRootButton(model, RWE)
				]
			)
		)
	)
	if retval:
		return GetRootValue(model, RWE)
	else:
		return None

def RweWithTextDialog(RWE, Header, FieldTag, defaultEntry):
	"""Display a dialog with an RWE choicebox and a Text field 
	and return a tuple (CVSRoot, Textfieldentry) or ("","") """
	model = PotGuiModel()
	model.SetValue(FieldTag, defaultEntry)
	theField = PotGuiTextView(FieldTag, TextView(), Point(300,100))
	retval=ShowSubDialog(Header,
		model,
		MakeSectionLayout(
			MakeBorderedSectionLayout("CVSROOT:", MakeRootButton(model, RWE)),
			MakeBorderedSectionLayout(FieldTag, theField)
		)
	)
	if retval:
		return (GetRootValue(model,RWE), model.GetValue(FieldTag))
	else:
		return ("","")

# need a global dialog variable for modeless dialg box
gShowFileDialog=None
def ShowText(Header, theFile):
	"""Display the contents of File in a non-modal Dialog with OK Button"""
	global gShowFileDialog
	model = PotGuiModel()
	model.SetValue("Text", theFile)
	if gShowFileDialog:
		# dispose of the old dialog
		del gShowFileDialog
	gShowFileDialog=PotGuiDialog(
		model,
		MakeDialogWithButtons(
			PotGuiTextView("Text", TextView(), Point(600,200)),
			ActionButton(CmdNo.cIdOk,"Close Window",1),
		),
		Header,
		eWinDefault
	)
	return gShowFileDialog.ShowUnderMouse()

def AskQuestionDialog(Header, Description="", defaultText="", bigEditor=0):
	"""Edit the contents of File in a modal Dialog with OK Button"""
	model = PotGuiModel()
	model.SetValue("Text", defaultText)
	if bigEditor:
		tv = PotGuiTextView("Text", TextView(), Point(600,300))
	else:
		tv = PotTextField("Text")
	rc=ShowSubDialog(Header,
		model,
		MakeSectionLayout(
			TextItem(str(Description)),
			tv
		)
	)
	if not rc: return None
	return model.GetValue("Text")

_ErrorDialogTimestamp=0
_ErrorDialogLastText=""
def ErrorDialog(Text, Title="Error", allowRepeat=1):
	global _ErrorDialogTimestamp, _ErrorDialogLastText
	curTime = time.time()
	diffTime = curTime - _ErrorDialogTimestamp
	if allowRepeat and _ErrorDialogLastText == Text and diffTime < 0.3:
		# if the same dialog was displayed less than 0.3 sec before, don't show again
		_ErrorDialogTimestamp = curTime
		return 1
	model = PotGuiModel()
	inner= Matte(
		gPointBorderGap,
		VExpander(
			items= (
				Filler(Point(0,10)),
				MultilineTextItem(Text),
				Filler(Point(0,15)),
				AlignBox(
					#eVObjHRight,
					eVObjHCenter,
					flags=eVObjVFixed,
					inner=HBox(
						align=eVObjVBase|eVObjHEqual,
						items=[
							ActionButton(CmdNo.cIdOk,"OK",default=1)
						]
					)
				)
			)
		)
	)
	dialog=PotGuiDialog(
		model,
		inner,
		Title,
	eWinBlock
	)
	retval = dialog.ShowUnderMouse()
	_ErrorDialogLastText = Text
	_ErrorDialogTimestamp = time.time()
	return retval


#----------Tests----------------------------------------------------------

if __name__ == '__main__':
		#retval = CVSDialogs.GuessRepositoryDialog("@TEST", "testLocal", "testRep", "testRoot")
		#retval = ShowPrefsDialog("")
		#retval = GetRepositoryDialog("", "Test")
		#retval = GetRepositoryDialog("@/Users/mober/TestArea/cvs2/rwefile", "Test")
		#retval = AddIgnoreDialog("TestRWE")
		#retval = ShowText("Test", "Hans-Petter-Lien")
		#retval = AskQuestionDialog("Editing Test", "Test Description", "Test Contents", 1)
		retval = ErrorDialog("Sorry, you do not have the right to do an exclusive checkout on this file.", "Sample Header")
		retval = ErrorDialog("Sorry, you do not have the right to do an exclusive checkout on this file.", "Sample Header")
		retval = ErrorDialog("Sorry, you do not have the right to do an exclusive checkout on this file.", "Sample Header")
		print retval
